package demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 最简单的Servlet
 * @author wupan
 */

public class MsgServlet extends HttpServlet {  
    /** 
     * 请求是get方式 
     */  
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{  
    	response.setCharacterEncoding("utf-8");
        //设置相应的类型为text/html  
        response.setContentType("text/html");   
        //对于get方式 获取请求文本参数的方法 getParameter(对应的键)  
        String parameValue=request.getParameter("p");  // http://127.0.0.1:8080/ServletDemo/showMsg?p=a
        //对客户端请求的数据进行操作  
        System.out.println(parameValue);  
          
        //从HttpServletResponse得到输出流  
        PrintWriter out = response.getWriter();   
        //向客户端打印HTML文本  
        out.write("<div>html格式响应文本</div>");   
          
        //输出并关闭流  
        out.flush();  
        out.close();  
    }  
    /** 
     * 请求是post方式 
     * 测试：curl -d "name=小明&score=19" "http://127.0.0.1:8080/ServletDemo/showMsg"
     */  
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{  
        //post的操作基本与get方式一致 但post不仅能传递文本 还能传递二进制流  
        InputStream io=request.getInputStream();  
        BufferedReader br=new BufferedReader(new InputStreamReader(io));  
        String line,reslult="";  
        while((line=br.readLine())!=null)  
            reslult+=line+"\n";  
        System.out.println(reslult);  
        io.close();  
        //其他操作……  
    }  
}  
